import { AnimationTask } from './animation.sjs';

const queryElement = (ownerInstance, classSelector) => {
  return ownerInstance.selectComponent(`.${classSelector}`);
};

let instance = null;
let mode = 'same';

const sliderLeftAnim = new AnimationTask(0, 5000, 1);

sliderLeftAnim.createTime = new Date().getTime();
console.log(`🚀 ~ sliderLeftAnim:`, sliderLeftAnim);

const sliderRightAnim = new AnimationTask(0, 5000, 1);

const sliderTracLeftAnim = new AnimationTask(0, 5000, 1);
const sliderTracRightAnim = new AnimationTask(0, 5000, 1);

let moveableLen, sliderWidth, viewWidth;
let startX = 0;
let movePosition;
let currentSliderMove = 0;
let currentSliderLeftMove = 0;
let currentSliderRightMove = 0;

const observerMode = modeProps => {
  mode = modeProps;
};

const observerLeftValue = (newValue, oldValue, ownerInstance) => {
  if (!instance) {
    instance = ownerInstance;
  }

  const moveableLen = getMoveableLen(ownerInstance);

  if (!moveableLen) return;
  const value = Math.min(100, Math.max(0, newValue));
  const len = (value * moveableLen) / 100;

  currentSliderLeftMove = len;
  sliderLeftAnim.setImmediate(len);
  // console.log(`🚀 ~ observerLeftValue ~ sliderLeftAnim.lastTime:`, sliderLeftAnim.lastTime);
  // sliderLeftAnim.setImmediate(len);
  // sliderTracLeftAnim.setImmediate(len);

  // sliderLeftAnim.maxChangedValue = moveableLen;
  // sliderTracLeftAnim.maxChangedValue = moveableLen;
  // 初始化动画参数
  if (!sliderLeftAnim.lastTime) {
    sliderLeftAnim.setImmediate(len);
    sliderTracLeftAnim.setImmediate(len);

    sliderLeftAnim.maxChangedValue = moveableLen;
    sliderTracLeftAnim.maxChangedValue = moveableLen;
  } else {
    // 变化超过 1% 时才触发动画更新
    if (Math.abs(sliderLeftAnim.value - len) >= moveableLen / 100) {
      sliderLeftAnim.startAnimation(len);
      sliderTracLeftAnim.startAnimation(len);
    } else {
      sliderLeftAnim.setImmediate(len);
      sliderTracLeftAnim.setImmediate(len);
    }
  }
};

const observerRightValue = (newValue, oldValue, ownerInstance) => {
  if (!instance) {
    instance = ownerInstance;
  }
  const moveableLen = getMoveableLen(ownerInstance);

  if (!moveableLen) return;
  const value = Math.min(100, Math.max(0, newValue));
  const len = (value * moveableLen) / 100;

  currentSliderRightMove = len;
  sliderRightAnim.setImmediate(len);

  // 初始化动画参数
  if (!sliderRightAnim.lastTime) {
    sliderRightAnim.setImmediate(len);
    sliderTracRightAnim.setImmediate(len);
    sliderRightAnim.maxChangedValue = moveableLen;
    sliderTracRightAnim.maxChangedValue = moveableLen;
  } else {
    // 变化超过 1% 时才触发动画更新
    if (Math.abs(sliderRightAnim.value - len) >= moveableLen / 100) {
      sliderRightAnim.startAnimation(len);
      sliderTracRightAnim.startAnimation(len);
    }
  }
};

const getCurrentPercent = value => {
  if (!moveableLen) return 0;

  const move = movePosition === 'left' ? currentSliderLeftMove : currentSliderRightMove;

  return Math.floor(((value || move) / moveableLen) * 100);
};

const getMoveableLen = ownerInstance => {
  if (moveableLen) return moveableLen;
  const container = queryElement(ownerInstance, 'container');
  const leftSlider = queryElement(ownerInstance, 'slider-left');
  if (!container || !leftSlider) return;
  const view = container.getBoundingClientRect();
  const leftView = leftSlider.getBoundingClientRect();
  console.log('🐫 ~ file: index.sjs:108 ~ leftView:', leftView, view);
  sliderWidth = leftView.width;
  viewWidth = view.width;
  moveableLen = view.width / 2 - leftView.width;
  return moveableLen;
};

const setSliderStyle = (ownerInstance, value, type) => {
  const leftSlider = queryElement(ownerInstance, 'slider-left');
  const rightSlider = queryElement(ownerInstance, 'slider-right');

  const leftSliderTrac = queryElement(ownerInstance, 'track_left');
  const rightSliderTrac = queryElement(ownerInstance, 'track_right');
  const move = Math.max(0, Math.min(moveableLen, value));

  // if()

  if (mode === 'single') {
    if (type === 'left') {
      leftSlider.setStyle({
        left: `${move}px`,
      });

      leftSliderTrac.setStyle({
        width: `${move + sliderWidth}px`,
      });

      currentSliderLeftMove = move;
    } else {
      rightSliderTrac.setStyle({
        width: `${move + sliderWidth}px`,
      });

      rightSlider.setStyle({
        right: `${move}px`,
      });

      currentSliderRightMove = move;
    }
  } else {
    leftSlider.setStyle({
      left: `${move}px`,
    });

    leftSliderTrac.setStyle({
      width: `${move + sliderWidth}px`,
    });

    rightSliderTrac.setStyle({
      width: `${move + sliderWidth}px`,
    });

    rightSlider.setStyle({
      right: `${move}px`,
    });
    currentSliderLeftMove = move;
    currentSliderRightMove = move;
  }

  // 不是由拖动引起的，不触发change事件
  if (!movePosition) return;

  const percent = getCurrentPercent();
  ownerInstance.triggerEvent('change', {
    value: percent,
  });
};

const setImageStyle = (ownerInstance, value) => {
  const leftImage = queryElement(ownerInstance, 'image-left');
  const rightImage = queryElement(ownerInstance, 'image-right');
  const move = Math.max(0, Math.min(moveableLen, value));
  leftImage.setStyle({
    width: `${move + sliderWidth}px`,
  });
  rightImage.setStyle({
    width: `${move + sliderWidth}px`,
  });
};

const setPercentStyle = ownerInstance => {
  const dialog = queryElement(ownerInstance, 'dialog-percent');
  const percent = getCurrentPercent();
  dialog.setStyle({
    '--percent-num': percent.toString(),
  });
};

sliderLeftAnim.onUpdate = function (value) {
  setSliderStyle(instance, value, 'left');
};

sliderRightAnim.onUpdate = function (value) {
  setSliderStyle(instance, value, 'right');
};

const handleStart = (event, ownerInstance) => {
  const { clientX } = event.touches[0];
  const { position } = event.currentTarget.dataset;
  // 没找到position？发生了异常
  if (!position || !['left', 'right'].includes(position)) return;

  movePosition = position;
  if (mode === 'single') {
    if (position === 'left') {
      sliderLeftAnim.stopAnimation();
      sliderTracLeftAnim.stopAnimation();
    } else {
      sliderRightAnim.stopAnimation();
      sliderTracRightAnim.stopAnimation();
    }
  } else {
    sliderLeftAnim.stopAnimation();
    sliderRightAnim.stopAnimation();

    sliderTracLeftAnim.stopAnimation();
    sliderTracRightAnim.stopAnimation();
  }

  startX = clientX;
  ownerInstance.callMethod('onSlidering');
  setPercentStyle(ownerInstance);
};

const handleMove = (event, ownerInstance) => {
  const { clientX } = event.touches[0];
  if (!movePosition) return;
  // 使用offsetLeft代替left
  if (movePosition === 'left') {
    const left = currentSliderLeftMove;
    const diff = clientX - startX;
    if (mode === 'single') {
      sliderLeftAnim.setImmediate(left + diff);
      sliderTracLeftAnim.setImmediate(left + diff);
    } else {
      sliderLeftAnim.setImmediate(left + diff);
      sliderTracLeftAnim.setImmediate(left + diff);
    }
    startX = clientX;
  } else if (movePosition === 'right') {
    const right = currentSliderRightMove;
    const diff = startX - clientX;
    if (mode === 'single') {
      sliderRightAnim.setImmediate(right + diff);
      sliderTracRightAnim.setImmediate(right + diff);
    } else {
      sliderLeftAnim.setImmediate(right + diff);
      sliderTracLeftAnim.setImmediate(right + diff);
      sliderRightAnim.setImmediate(right + diff);
      sliderTracRightAnim.setImmediate(right + diff);
    }
    startX = clientX;
  }
  setPercentStyle(ownerInstance);
};

const handleEnd = (event, ownerInstance) => {
  const percent = getCurrentPercent();
  ownerInstance.triggerEvent('changend', {
    value: {
      percent,
      type: mode == 'single' ? movePosition : '',
    },
  });

  movePosition = '';
  ownerInstance.callMethod('onSliderEnd');
};

let lastControl = '';
const controlChange = (newControl, oldControl, ownerInstance) => {
  console.log('newControl', newControl);
  if (newControl !== lastControl) {
    lastControl = newControl;
    if (newControl === 'stop') {
      // sliderAnim.stopAnimation();
    } else if (newControl === 'continue') {
    }
  }
};

module.exports = {
  handleStart,
  handleMove,
  handleEnd,
  controlChange,
  observerMode,
  observerLeftValue,
  observerRightValue,
};
